package me.msz.learning.rest.resources;

import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * Root resource (exposed at "simple-calculator" path)
 */
@Path("simple-calculator")
public class CalculatorResource {

    @GET
    @Path("/{opname}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response doOp(@PathParam("opname") String opname, @QueryParam("parameter_a") double parameter_a,
                         @QueryParam("parameter_b") double parameter_b) {
        double result = 0.0;
        String retEntity = new String();
        switch(opname) {
            case "add":
                result = parameter_a + parameter_b;
                break;
            case "substract":
                result = parameter_a - parameter_b;
                break;
            case "multiply":
                result = parameter_a * parameter_b;
                break;
            case "divide":
                if(parameter_b == 0.0) {
                    retEntity = "[错误] 除法第二个操作数不能为0";
                } else {
                    result = parameter_a / parameter_b;
                }
                break;
            default:
                retEntity = "[错误] 没有指定操作";
                break;
        }
        if(retEntity.isEmpty()) {
            retEntity = "对操作数" + parameter_a + "和" + parameter_b + "进行操作[" + opname +"]的计算结果为：" + result;
        }
        return Response.status(200).entity(retEntity).encoding("UTF-8").build();
    }

    @POST
    @Produces(MediaType.TEXT_PLAIN)
    public Response processEquation(String equations) {
        int statusCode = 200;
        String retEntity = new String();
        String[] equationArray = equations.trim().replaceAll("\\s*", "").split(";");
        for(String equation : equationArray) {
            Expression exp = new ExpressionBuilder(equation).build();
            double result = exp.evaluate();
            retEntity += "The Value of " + equation.trim() + " is " + result + "\n";
        }
        return Response.status(statusCode).entity(retEntity).encoding("UTF-8").build();
    }
}
